import React, { useState, useRef, useEffect } from 'react'
import { Modal } from 'antd'
import './index.css'
import { DockerOutlined, SendOutlined, RedditOutlined, DeleteOutlined, PictureOutlined } from '@ant-design/icons'
import { Avatar } from 'antd'
import { useTranslation } from 'react-i18next'

interface ChatModalProps {
  open: boolean
  onClose: () => void
  title?: string
  width?: number | string
}

interface Message {
  role: string
  content: string
  type?: 'text' | 'image'
  imageUrl?: string
}

const ChatModal: React.FC<ChatModalProps> = ({
  open,
  onClose,
  width = '80%',
}) => {
  const { t } = useTranslation()
  const [message, setMessage] = useState<string>('')
  const [server, setServer] = useState<Message[]>([])
  const [selectedImage, setSelectedImage] = useState<File | null>(null)
  const [imagePreview, setImagePreview] = useState<string | null>(null)
  const [uploading, setUploading] = useState<boolean>(false)

  // 新增：本地历史键与输入框ref
  const HISTORY_KEY = 'chatmodal_history'
  const inputRef = useRef<HTMLInputElement>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  // 新增：内容区ref用于自动滚动到底
  const contentRef = useRef<HTMLDivElement>(null)

  // 图片上传配置
  const MAX_FILE_SIZE = 5 * 1024 * 1024 // 5MB
  const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']

  // 新增：页面加载时获取历史记录
  useEffect(() => {
    try {
      const raw = localStorage.getItem(HISTORY_KEY)
      if (raw) {
        const list = JSON.parse(raw)
        if (Array.isArray(list)) {
          setServer(list)
        }
      }
    } catch { }
  }, [])

  // 新增：server变化时保存到本地
  useEffect(() => {
    try {
      localStorage.setItem(HISTORY_KEY, JSON.stringify(server))
    } catch { }
  }, [server])

  // 新增：消息更新后自动滚动到底部
  useEffect(() => {
    const el = contentRef.current
    if (el) {
      el.scrollTop = el.scrollHeight
    }
  }, [server])

  // 新增：打开弹框时也滚到底，避免历史加载后位置不正确
  useEffect(() => {
    if (open) {
      const el = contentRef.current
      if (el) {
        el.scrollTop = el.scrollHeight
      }
    }
  }, [open])

  // 处理图片选择
  const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    // 验证文件类型
    if (!ALLOWED_TYPES.includes(file.type)) {
      alert('只支持JPG、PNG、GIF和WebP格式的图片')
      return
    }

    // 验证文件大小
    if (file.size > MAX_FILE_SIZE) {
      alert('图片大小不能超过5MB')
      return
    }

    setSelectedImage(file)

    // 创建预览
    const reader = new FileReader()
    reader.onload = (e) => {
      setImagePreview(e.target?.result as string)
    }
    reader.readAsDataURL(file)
  }

  // 取消图片选择
  const cancelImageSelection = () => {
    setSelectedImage(null)
    setImagePreview(null)
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
    }
  }

  // 发送图片消息
  const sendImageMessage = async () => {
    if (!selectedImage) return

    try {
      setUploading(true)

      // 这里是模拟上传，实际项目中应该调用真实的上传API
      // 为了演示，我们直接使用FileReader创建的DataURL
      const imageUrl = imagePreview

      // 添加图片消息到聊天记录
      setServer(prev => [...prev, {
        role: 'user',
        content: `[图片]`,
        type: 'image',
        imageUrl: imageUrl as string
      }])

      // 清理状态
      setSelectedImage(null)
      setImagePreview(null)
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
      }

      // 可以在这里添加对图片的AI回复逻辑
      // await Handlerequest(`用户发送了一张图片`)

      setUploading(false)
    } catch (error) {
      alert('图片上传失败')
      setUploading(false)
    }
  }

  const Handlerequest = async (message: string) => {
    const res = await fetch('https://qianfan.baidubce.com/v2/chat/completions', {
      headers: {
        'Authorization': 'Bearer bce-v3/ALTAK-nYZffwROwdzfXU9bBu8Rm/4829d4b20e2024b00549383ab509ae4fabe31268',
        'Content-Type': 'ernie-4.5-turbo-128k'
      },
      method: 'POST',
      body: JSON.stringify({
        model: 'ernie-4.5-turbo-128k',
        messages: [
          {
            role: 'user',
            content: message
          }
        ]
      })
    })
    const data = await res.text()
    const result = JSON.parse(data)
    setServer((prev) => [...prev, { ...result.choices[0].message, type: 'text' }])
  }

  const sendMeeageHandler = () => {
    if (message.trim() !== '') {
      setServer((prev) => [...prev, { role: 'user', content: message, type: 'text' }])
      Handlerequest(message)
      // 新增：发送完成清空输入框与状态
      if (inputRef.current) inputRef.current.value = ''
      setMessage('')
    }
  }

  // 新增：清空当前与历史记录按钮逻辑
  const clearAllHandler = () => {
    setServer([])
    try { localStorage.removeItem(HISTORY_KEY) } catch { }
  }

  return (
    <Modal
      open={open}
      onCancel={onClose}
      footer={null}
      width={width}
      centered
      maskClosable
    >
      <div className='container'>
        <div className="header">
          <div className="title">
            <RedditOutlined className='logo' />
            <h2 className='logo-text'>{t('chat_title')}</h2>
            {/* 新增：清空消息按钮 */}
            <button
              className='clear-btn'
              onClick={clearAllHandler}
            ><DeleteOutlined style={{ marginRight: 5 }} />{t('clear')}</button>
          </div>
        </div>
        <div className="content" ref={contentRef}>
          {server.length === 0 && <p className='content-state'>{t('no_messages')}</p>}
          {server.map((item, index) => (
            <div key={index} className={`message ${item.role} content-${item.role}`}>
              {item.role === 'assistant' && (<Avatar size={40} icon={<DockerOutlined className='DockerOutlined' />} />)}
              {item.type === 'image' ? (
                <div className="image-container">
                  <img src={item.imageUrl} alt="聊天图片" className="chat-image" />
                </div>
              ) : (
                <p>{item.content}</p>
              )}
            </div>
          ))}
        </div>

        {/* 图片预览区域 */}
        {imagePreview && (
          <div className="image-preview-container">
            <img src={imagePreview} alt="预览" className="preview-image" />
            <button className="cancel-preview" onClick={cancelImageSelection}>取消</button>
          </div>
        )}

        <div className="footed">
          <form action='#' className='chart-form' onSubmit={(e) => { e.preventDefault(); sendMeeageHandler() }}>
            <input
              type="text"
              className="message-input"
              placeholder={t('input_placeholder')}
              required={!selectedImage}
              onChange={(e) => setMessage(e.target.value)}
              ref={inputRef}
              disabled={!!selectedImage}
            />

            {/* 隐藏的文件输入 */}
            <input
              type="file"
              accept="image/jpeg,image/png,image/gif,image/webp"
              style={{ display: 'none' }}
              ref={fileInputRef}
              onChange={handleImageSelect}
            />

            {/* 图片上传按钮 */}
            <button
              type="button"
              className="upload-btn"
              onClick={() => fileInputRef.current?.click()}
              disabled={!!selectedImage || uploading}
            >
              <PictureOutlined />
            </button>

            {/* 发送按钮 - 根据是否有选中图片显示不同行为 */}
            {selectedImage ? (
              <button
                type="button"
                className='message-send'
                onClick={sendImageMessage}
                disabled={uploading}
              >
                {uploading ? '上传中...' : '发送图片'}<SendOutlined className='sendbtn' />
              </button>
            ) : (
              <button
                className='message-send'
                onClick={() => sendMeeageHandler()}
              >
                {t('send')}<SendOutlined className='sendbtn' />
              </button>
            )}
          </form>
        </div>
      </div>
    </Modal>
  )
}

export default ChatModal